<?php
/*
 * @Author: your name
 * @Date: 2019-11-18 13:23:58
 * @LastEditTime : 2020-01-07 19:07:45
 * @LastEditors  : Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /ahsmp_3/application/common/service/HostLink.php
 */

namespace app\common\service;


class HostLink extends Base 

{
    /**
     * @name: 查找单个模块的联系地址
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-09 13:52:24
     */
    function findOne ($hostId, $module)
    {
        $return = db('HostLink')->field('ip,port')->where('host_id', $hostId)->where('module', $module)->find();
        
        return $return;
    }

    /**
     * @name: 模块是否在线
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-26 16:42:28
     */
    function checkOnline ($module)
    {
        $hostId_a = $this->getHost('id');
        $offlineHost = db('HostLink')->whereIn('host_id', $hostId_a)->where('module', $module)->where('status', 0)->column('host_id');

        if($offlineHost)
        {
            $this->setError($this->CODE_FAIL, $this->hostErrorMessage($offlineHost, '已离线'));
            return false;
        }
    }

    /**
     * @name: 添加
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-30 14:04:36
     */
    function add ($module, $hostId_a)
    {
        if(empty($hostId_a))
        {
            return [];
        }

        $insertData = array_map(function($host_id) use ($module)
        {
            $data = [
                'host_id' => $host_id,
                'module' => $module,
                'ip' => 0,
                'port' => 0,
                'status' => 0,
            ];
            return "('" . implode("','", $data) . "')";
        }, $hostId_a);
        db()->query('INSERT IGNORE INTO `' . config('database.prefix') .'host_link` (`host_id`, `module`, `ip`, `port`, `status`) VALUES ' . implode(',', $insertData));
    }
    
    /**
     * @name: 主机离线
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-01-07 17:59:31
     */
    function offline ($hostId_a, $module)
    {
        db('HostLink')->whereIn('host_id', $hostId_a)->where('module', $module)->update(['status' => 0]);
    }

    /**
     * @name: 修改版本
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-01-07 19:06:17
     */
    function updateVersion ($host_id, $module, $version)
    {
        db('HostLink')->where('host_id', $host_id)->where('module', $module)->update(['version' => $version]);
    }
}